package com.example.shutdown_v1.controller;

import com.example.shutdown_v1.service.PowerDeviceService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;
import java.util.concurrent.CompletableFuture;

/**
 * 兼容旧版前端使用的电力查询接口：/api/power/default/query/all/sync
 * 新代码请优先使用 /api/power-device/{merchantId}/query/all/sync
 */
@Slf4j
@RestController
@RequestMapping("/api/power")
@CrossOrigin(originPatterns = "*")
@RequiredArgsConstructor
public class LegacyPowerApiController {

    private final PowerDeviceService powerDeviceService;

    /**
     * 兼容旧路径：查询默认商家的所有路电力状态（同步执行）
     * 对应旧前端调用 POST /api/power/default/query/all/sync
     */
    @PostMapping("/default/query/all/sync")
    public ResponseEntity<Map<String, Object>> queryAllChannelsForDefault() {
        String merchantId = "default";
        try {
            log.info("[兼容API] 旧路径全路查询 - 商家:{}", merchantId);

            // 与 PowerDeviceController.queryAllChannelsSync 逻辑保持一致
            CompletableFuture<Map<Integer, Boolean>> future = powerDeviceService.queryAllChannels(merchantId);
            Map<Integer, Boolean> results = future.get();

            Map<String, Object> fullStatus = powerDeviceService.getMerchantPowerStatus(merchantId);

            return ResponseEntity.ok(Map.of(
                    "success", true,
                    "message", "全路查询完成(兼容旧API)",
                    "merchantId", merchantId,
                    "queryResults", results,
                    "merchantStatus", fullStatus
            ));
        } catch (Exception e) {
            log.error("[兼容API] 旧路径全路查询失败 - 商家:{}", merchantId, e);
            return ResponseEntity.internalServerError().body(Map.of(
                    "success", false,
                    "message", "查询失败: " + e.getMessage(),
                    "merchantId", merchantId
            ));
        }
    }
}
